﻿using SmartSapce.ServiceLocation;
using SmartSpace.Core;
using SmartSpace;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Web;
using System.Web.UI.WebControls.WebParts;

namespace SmartSpace.WebApp
{
    public partial class _shell : System.Web.UI.Page
    {
        private Guid _applicationId;
        private Guid _navigationId;
        private string _viewsString;
        private string _pageName;
        private List<SmartSpace.Web.ViewInfo> _viewInfos = new List<SmartSpace.Web.ViewInfo>();

        protected override void OnPreInit(EventArgs e)
        {
            if (this.User == null || !this.User.Identity.IsAuthenticated
                || string.IsNullOrEmpty(this.User.Identity.Name))
            {
                Response.Redirect("./login.aspx");
            }
            else
            {
                try
                {
                    if (!string.IsNullOrEmpty(Request.QueryString["ss:page"]))
                    {
                        _pageName = Request.QueryString["ss:page"];
                    }

                    Logger.Debug(string.Format("visit page {0} ,app{1}", _pageName, SsSite.HostUrl));

                    ICoreService service = ServiceLocator.Get<ICoreService>();
                    Site site = SsSite.Current;
                    User user = service.GetUser(User.Identity.Name);
                    SiteTemplate theme = service.GetSiteTemplate(site.TemplateId);
                    List<Shortcut> shortcuts = service.GetShortcuts(site.Id);
                    ListResult<Nav> navigations = service.GetNavigations(site.Id);
                    List<Site> applications = service.GetSites();

                    //System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFile(Server.MapPath("~/" + theme.Package));

                    //SmartSpace.Web.ISiteTemplate themeInstance = (SmartSpace.Web.ISiteTemplate)assembly.CreateInstance(theme.Name);
                    SmartSpace.Web.IMainPanel mainPanel = this.LoadControl(string.Format("~/Templates/{0}/MainPanel.ascx", theme.Code)) as IMainPanel;
                    if (mainPanel != null)
                    {

                        Control mycontrol = mainPanel.GetContentView();
                        this._panel.Controls.Add(mycontrol);

                        mainPanel.GetHeaderPanel().Initiate(navigations.Data, shortcuts, applications, site, user);
                        mainPanel.GetNavigatePanel().Initiate(navigations.Data, shortcuts);

                        mainPanel.GetHeaderPanel().Logoff += new SmartSpace.Web.LogoffEventHandler(_shell_Logoff);
                        mainPanel.GetNavigatePanel().Navigating += _shell_Navigating;

                        SmartSpace.Core.Page page = service.GetPage(SsSite.Current.Id, _pageName);
                        this.Title = page.Caption;
                        mainPanel.GetWorkAreaPanel().SwitchView(this.LoadControl("~/Templates/Page/" + page.Template.Code + ".ascx"));
                    }
                    else
                    {
                        Logger.Error(string.Format("could not create template instance '{0}' from '{1}'", theme.Name, "~/Templates/Sites/Prototype/MainPanel.ascx"));
                    }
                }
                catch (Exception ex)
                {
                    Logger.Debug(string.Format("visit page error {0} ,{1}", Request.Url.OriginalString, ex.Message), ex);
                }

                base.OnPreInit(e);
            }
        }

        void viewInstance_SwitchView(object sender, SwitchEventArgs e)
        {
            string originalViewString = string.Empty;

            foreach (var viewInfo in _viewInfos)
            {
                originalViewString += string.Format("{0}[{1}]/",
                    viewInfo.VirtualPath,
                    viewInfo.Arguments);
            }

            originalViewString += string.Format("{0}[{1}]/",
                e.VirtualPath,
                e.Arguments);

            originalViewString = Convert.ToBase64String(Encoding.UTF8.GetBytes(originalViewString));

            Response.Redirect(Request.Url.AbsolutePath + string.Format("?id={0}&nid={1}&__views={2}",
                _applicationId,
                _navigationId,
                originalViewString));
        }

        void _shell_Navigating(object sender, NavigatingEventArgs e)
        {
            Response.Redirect(Request.Url.AbsolutePath + string.Format("?id={0}&nid={1}", _applicationId, e.Navigation.Id.ToString()));
        }

        void _shell_Logoff(object sender, SmartSpace.Web.LogoffEventArgs e)
        {
            Response.Redirect("~/_logoff.aspx");
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            ICoreService service = ServiceLocator.Get<ICoreService>();
            List<Module> modules = service.GetModules(0, 9999);

            _ctlWebPartManager.DisplayMode = WebPartManager.BrowseDisplayMode;
            for (int index = 0; index < _ctlWebPartManager.Zones.Count; index++)
            {
                WebPartZoneBase zone = _ctlWebPartManager.Zones[index];
                zone.WebPartVerbRenderMode = WebPartVerbRenderMode.TitleBar;
                for (int iWebPart = 0; iWebPart < zone.WebParts.Count; iWebPart++)
                {
                    WebPart part = zone.WebParts[iWebPart];
                    part.AllowClose = false;
                    part.AllowMinimize = false;
                }
            }
        }
    }
}